﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FullThrustLogic.Core.GameState;

namespace FullThrustLogic.Core
{
    public class GameContext
    {
        private iGameState _currentState;
        private bool _gameFinished = false;

        public Map Map { get;set; }

        public List<Player> Players { get; set; }

        public int TotalNumberOfRounds {  get;  set; }

        public int RoundNumber  {  get; set; }

        public delegate void GameStateChangedHandler(object sender, EventArgs e);
        public event GameStateChangedHandler OnGameStateChanged;

        public GameContext()
        {
            _currentState = new CreateGameState(this);
            _currentState.OnGameStateChanged += new GameStateChangedHandler(_currentState_OnGameStateChanged);
        }

        public iGameState CurrentState
        {
            get { return _currentState; }
        }

        void _currentState_OnGameStateChanged(object sender, EventArgs e)
        {
            if(CurrentState is CreateGameState)
            {
                _currentState = new MovementState(this);

                _currentState.OnGameStateChanged -= new GameStateChangedHandler(_currentState_OnGameStateChanged);
                _currentState.OnGameStateChanged +=new GameStateChangedHandler(_currentState_OnGameStateChanged);
            }
            else if (CurrentState is MovementState)
            {
                _currentState = new AttackOrderState(this);

                _currentState.OnGameStateChanged -= new GameStateChangedHandler(_currentState_OnGameStateChanged);
                _currentState.OnGameStateChanged += new GameStateChangedHandler(_currentState_OnGameStateChanged);

                if (Players[(int)((AttackOrderState)_currentState).ControllingPlayer].AvailableToAttackShips.Count == 0)
                {
                    ((AttackOrderState)_currentState).GetNextPlayer();
                }
            }
            else if (CurrentState is AttackOrderState)
            {
                if (_gameFinished)
                {
                    _currentState = new EndGameState(this);
                }
                else
                {
                    _currentState = new MovementState(this);
                }

                _currentState.OnGameStateChanged -= new GameStateChangedHandler(_currentState_OnGameStateChanged);
                _currentState.OnGameStateChanged += new GameStateChangedHandler(_currentState_OnGameStateChanged);
            }
            else if (CurrentState is EndGameState)
            {
                
            }

            if(OnGameStateChanged != null)
            {
                OnGameStateChanged(this, new EventArgs());
            }
        }

    }
}
